package com.tianji.login.cookie;

import com.tianji.common.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * Description: cookie的测试
 *
 * @author chenjia
 * @version 1.0
 * @date 2024/11/13 10:42
 */
@RestController
@RequestMapping("cookie")
@Api(value = "cookie的测试控制器")
public class CookieController {

    @ApiOperation(value = "获取cookie")
    @GetMapping("/getCookie")
    public Result getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            Arrays.stream(cookies).forEach(cookie -> {
                System.out.println(cookie.getName() + "=" + cookie.getValue());
            });
        }
        return Result.success();
    }

    @ApiOperation(value = "获取cookie简化")
    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("name") String name){
        return "从Cookie中获取值, name:"+name;
    }

    @ApiOperation(value = "获取session")
    @RequestMapping("/getSession")
    public Result getSession(HttpServletRequest request){
        //从cookie中获取到了sessionID, 根据session获取Session对象
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return Result.success(name);
    }

    @ApiOperation(value = "获取session简化")
    @RequestMapping("/getSession2")
    public Result getSess2(HttpSession session){
        String name = (String)session.getAttribute("name");
        return Result.success(name);
    }

    @ApiOperation(value = "获取session简化")
    @RequestMapping("/getSession3")
    public Result getSess3(@SessionAttribute("name") String name){
        return Result.success(name);
    }

    @ApiOperation(value = "获取请求头")
    @RequestMapping("/getHeader")
    public Result getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return Result.success(userAgent);
    }

    @ApiOperation(value = "获取请求头简化")
    @RequestMapping("/getHeader2")
    public Result getHeader2(@RequestHeader("User-Agent") String userAgent){
        return Result.success(userAgent);
    }
}
